package com.education.platform.common.web;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 返回响应
 */
@ControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice {





    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        final String returnTypeName = methodParameter.getParameterType().getName();
        return  !"com.education.platform.common.web.ResponseEntity".equals(returnTypeName)
                && !"org.springframework.http.ResponseEntity".equals(returnTypeName);
    }





    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (!mediaType.includes(MediaType.APPLICATION_JSON)) {
            return o;
        }
        ResponseEntity responseEntity = new ResponseBuilder()
                .code(ResponseCode.SUCCESS.getCode())
                .message(ResponseCode.SUCCESS.getDesc())
                .data(o)
                .build();
        return responseEntity;
    }


}
